package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description:
 * @Title: AddressBookController
 * @Package com.itheima.reggie.controller
 * @Author: 🐟
 * @Copyright 🐟
 * @CreateTime: 2022/9/15 21:31
 */
@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public R<String> addAddress(@RequestBody AddressBook addressBook, HttpServletRequest request) {
        addressBookService.addAddress(addressBook, request);
        return R.success("保存地址成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> getaddress(HttpServletRequest request) {
        Long user = (Long) request.getSession().getAttribute("User");
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(AddressBook::getUserId, user);
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);

    }

    @PutMapping("/default")
    public R<String> setdefault(@RequestBody AddressBook addressBook) {

        addressBookService.setdefault(addressBook);
        return R.success("设置成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> getAddressById(@PathVariable Long id) {
        AddressBook byId = addressBookService.getById(id);
        return R.success(byId);
    }

    @GetMapping("/default")
    public R<AddressBook> getAddressBookByIdAndis_default() {
        AddressBook addressBook = addressBookService.getAddressBookByIdAndis_default();
        return R.success(addressBook);
    }

    @DeleteMapping
    public R<String> delectByIds(@RequestParam("ids") List<Long> ids) {
        boolean b = addressBookService.removeByIds(ids);
        if (b) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }
    @PutMapping
    public R<String> updateAddressByAllInfo(@RequestBody AddressBook addressBook){
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookService.updateById(addressBook);
        return R.success("修改成功");

    }

}
